<template>
  <div class="box">
    <TopSearch
      @searchHeader="searchHeader"
      @delsHeader="delsHeader"
      @addHeader="addHeader"
      :control="control"
      :controlPosition="controlPosition"
      :positionName="positionName"
      :disabled="disabled"
      :delsable="delsable"
      :searchConfig="setFormConfig"
    >
    <template #add ><el-button @click="addHeader" v-permission="'course/create'" color="#50BC58"  icon="Plus" circle class="ml-4 " style="color:#fff"></el-button></template>
        <template #DataImport >
        <el-button class="ml-10 button"  color="#2292A4" @click="Import" >
         <div class="flex items-center">
           <img src="@/assets/icon/import.png" alt="">
          <div class="ml-[10px]"> 數據導入</div>
         </div>
        </el-button>
    </template>
    </TopSearch>
    
    <ProTable
      class="protable"
      :data="tableData"
      :page="page"
      :column="column"
      :rowControl="rowControl"
      :elProps="elProps"
      :disabled="disabled"
      :controlWidth="controlWidth"
      @row-control-click="onRowControlClick"
      @selection-change="onSelectionChange"
      @page-change="onPageChange"
      @pageRefresh="pageRefresh"
    >
      <template #default="{ row, propname }">
        <div v-if="propname === 'teacher'  ">
            {{row[propname]?.name}}
        </div>
      </template>
              <template #search_operate>
            <el-table-column  fixed="right" min-width="200px" label="操作">
              <template #default="scope" >
                <div class="flex justify-around">
                <el-link v-permission="'course/update'"  @click="onRowControlClick(scope.row, 'rowedit')" type="primary" :underline="false" >查看</el-link >
                <el-link @click="onRowControlClick(scope.row, 'rowcopy')" type="primary" :underline="false" >複製</el-link >
                <el-link v-permission="'course/delete'"  @click="onRowControlClick(scope.row, 'rowdel')" type="primary" :underline="false" >刪除</el-link >
                </div>
              </template>
            </el-table-column>
        </template>
    </ProTable>
    <FouDialog
      :title="'添加/修改'"
      :width="'75%'"
      v-model:dialogValue="dialogValue"
    >
      <template #content>
        <div>
          <addEdit ref="AddEditref" @change="change" :echo="echo" :courseList="courseList" :teacherSelect="teacherSelect" :classroomSelect="classroomSelect" ></addEdit>
        </div>
      </template>
      <template #footer>
        <div>
          <el-button @click="dialogValue = false">取消</el-button>
          <el-button type="primary" @click="confirm(buttonType)" color="#081F42"
            >確定</el-button
          >
        </div>
      </template>
    </FouDialog>

                  <FouDialog
      :title="'是否下載學生資料導入格式模板'"
      :width="'30%'"
      v-model:dialogValue="excelDiolog"
    >
      <template #content>
        <div><el-icon><WarningFilled /></el-icon>按照規定excel格式導入，可選擇下載當前模板進行格式對比，避免格式不正確導致數據丟失！注意：凡帶有(必填)字樣信息為必填，不填為空系統默以異常數據處理，帶有(參考)字樣需按照網站現有值進行填寫</div>
      </template>
      <template #footer>
          <el-button size="small" @click="onDownExcel">參考規則 (下載模板)</el-button>
          <el-button size="small" type="primary" @click="onImportExcel">已按照規定規則 (繼續導入)</el-button>
      </template>
    </FouDialog>
      <input v-show="false" type="file" accept=".xlsx,.xls" ref="inputUpload" @change="importExcel" /> 
        <FouDialog
      :title="'導入數據展示'"
      :width="'90%'"
      v-model:dialogValue="excelTableShow"
    >
    <template #content>
        <excelTableList :excelTable="excelTable"></excelTableList>
    </template>
    <template #footer>
          <el-button @click="excelTableShow = false" >取消</el-button>
          <el-button color="#081F42" @click="ImportStudent(excelTable)" >確認導入</el-button>
    </template>
    </FouDialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { elProps, options, controlWidth } from "./index.js";
import { setFormConfig } from "./formConfig";
import addEdit from "./addEdit/index.vue"; 
import { course, addCourse, updateCourse,delCourse,coursecate,teacherList,excelCreate,classroomList } from "@/http/index.js";
 import excelTableList from './excelTable.vue'

import { dayjs } from "element-plus";
import {messageBox,message,loading,closeLoading } from "@/common/function.js";
import bus from '@/common/bus.js'
import * as XLSX from "xlsx";
 import {exportExcel} from '@/common/excel.js'

// import sales from '@/assets/icon/sales.svg'
const echo = ref({});
  const excelData = [
    ['課程名稱(必填)','上課時間(必填)','下課時間(必填)','上課人數(必填)','備註','摘要','價格(必填)','星期(必填)','課程分類(必填)','教練(必填)'],
    ['測試課程', '2023-05-12 10:54:54', '2023-05-12 10:54:54', '5', '備註', '摘要', '100', '1,2,', '大班', '高教練'],
  ]; // 导出的表格名称
// 數據導入
const excelDiolog = ref(false)
const Import = ()=>{
   excelDiolog.value = true
}
const onDownExcel = ()=>{
  exportExcel(excelData,'課程列表.xlsx','課程')
  excelDiolog.value = false
}
const inputUpload = ref('')
const onImportExcel = ()=>{
  inputUpload.value.click()
  excelDiolog.value = false
}
const excelTable = ref([])
const excelTableShow = ref(false)
const importExcel = (file)=>{
      // 获取上传的文件对象
      const { files } = file.target;
      // 通过FileReader对象读取文件
      const fileReader = new FileReader();
      fileReader.onload = (event) => {
        try {
          const { result } = event.target;
          // 以二进制流方式读取得到整份excel表格对象
          const workbook = XLSX.read(result, { type: "binary" });
          let data = []; // 存储获取到的数据
          // 遍历每张工作表进行读取（这里默认只读取第一张表）
          for (const sheet in workbook.Sheets) {
            if (Object.prototype.hasOwnProperty.call(workbook.Sheets,sheet)) {//这是关键的一步，hasOwnPropert要从Object的原型中调用
              // 利用 sheet_to_json 方法将 excel 转成 json 数据
              data = data.concat(
                XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
              );
              // break; // 如果只取第一张表，就取消注释这行
            }
          }
          console.log(data);
          let arr = []
          //  ['學生姓名(必填)','電話(必填)','登錄名(必填)','密碼(必填)','電子郵箱','學生地址','英文名','學生來源','備註','性別(必填)','狀態','調課次數(必填)','生日',
          //  '身份證','學生類型(必填)','學歷','卡號(必填、十位數字)','聯絡人名稱(必填)','與學生關係(必填)','聯絡人聯絡電話(必填)','住宅電話','聯絡人地址'],
          data.forEach(item => {
            let obj = {}
            '課程名稱(必填)','上課時間(必填)','下課時間(必填)','上課人數(必填)','備註','摘要','價格(必填)','星期(必填)','課程分類(必填)','教練(必填)'
            obj.name = item["課程名稱(必填)"]
            obj.start_time = item["上課時間(必填)"]
            obj.end_time = item["下課時間(必填)"]
            obj.num = item["上課人數(必填)"]
            obj.remark = item["備註"]
            obj.digest = item["摘要"]
            obj.price = item["價格(必填)"]
            obj.week = item["星期(必填)"]
            obj.course_category = item["課程分類(必填)"]
            obj.admins = item["教練(必填)"]
            arr.push(obj)
          })
            excelTable.value= arr

          excelTableShow.value = true
        } catch (e) {
          // 这里可以抛出文件类型错误不正确的相关提示
          console.log(e);
          message('文件类型不正确,請刷新後再試',"warning")
          return;
        }
      };
      // 以二进制方式打开文件
      fileReader.readAsBinaryString(files[0]);
}
const ImportStudent = async(e)=>{
  console.log(e);
  const data = await excelCreate(JSON.stringify(e))
  if (data.code == 200) {
        tableList();
        excelTableShow.value = false
    message('導入課程成功')
  }else{
      message(data.msg,'warning')
    }
}


const change = (e)=>{
console.log(e);
}
// 添加編輯彈窗
const AddEditref = ref(null);
const confirm = (type) => {
  AddEditref.value.DialogCofirm(async (e) => {
  let params = JSON.parse(JSON.stringify(e));
    if (params.week) {
      params.week = params.week.toString()
    }
    if (params.date) {
        params.start_time = params.date[0]
        params.end_time = params.date[1]
        delete params.date
    }
    if (params.admins_id) {
      params.admins_id = params.admins_id.toString()
    }
    console.log(params);
      if (type == "add") {
        if (params.id) {
          delete params.id;
        }
        await addTableList(params);
        dialogValue.value = false;
      }
      if (type == "copy") {
        if (params.id) {
          delete params.id;
        }
        await addTableList(params);
        dialogValue.value = false;
      }
      if (type == "edit") {
        await updateTableList(params);
        dialogValue.value = false;
      }
  });
};
// 修改课程
const updateTableList = async (e) => {
  const data = await updateCourse(e);
  if (data.code == 200) {
    tableList();
    message('修改課程成功')
  }
};
// 添加课程
const addTableList = async (e) => {
  console.log(e);
  const data = await addCourse(e);
  console.log(data);
  if (data.code == 200) {
    tableList();
    message('添加課程成功')
  }else{
    message('添加課程失敗')
  }
};
// 分页数据（不给就没有分页）
const page = reactive({
  current_page: 1, //当前页
  per_page: 10, //每页条数
  total: 10, //总条数
  page_size: [10, 20, 30], //可选分页条数
});
// 字段名对应表头
const column = {
  name: "課程名稱",
  number: "編號",
  start_time:"上課日期",
  end_time:'下課日期',
  statuss: "狀態",
  create_time: "發佈時間",
  num:'上課人數',
  time:'上課時間',
  week:'星期',
  price:'價格',
  remark:'備註',
  teacher:'教練'
};
// 表格顶部操作按钮
const control = ["search", "dels"];
const controlPosition = [];
const positionName = ref("");

// 未选中数据是 禁用项
const disabled = ["dels"];
const delsable = ref(true);

const searchHeader =async (e, type) => {
  Object.assign(obj, e);
  await tableList(obj);
};

const dialogValue = ref(false);
const buttonType = ref("");

const courseList = ref([])
const teacherSelect = ref([])
const classroomSelect = ref([])
const getCourseCate = async()=>{
  loading()
    let obj = {limit:100}
  const data = await coursecate(obj)
  if (data.code == 200) {
    data.data.data.map((e)=>{e.label = e.name,e.value = e.id})
    courseList.value = data.data.data
  }else{message('獲取課程分類失敗,請刷新重試')}
  closeLoading()
}
const getTeacherList = async()=>{
  loading()
  let obj = {limit:100,school_id:localStorage.getItem('school_id')}
  const data = await teacherList(obj)
  if (data.code == 200) {
  teacherSelect.value = data.data.data
  }else{message('獲取教師列表失敗,請刷新重試')}
  closeLoading()
}
const getclassRoom = async()=>{
  loading()
  let obj = {limit:100,school_id:localStorage.getItem('school_id')}
  const data = await classroomList(obj)
  if (data.code == 200) {
    classroomSelect.value = data.data.data
  }else{message('獲取教室列表失敗,請刷新重試')}
  closeLoading()
}

const addHeader = async() => {
  await getCourseCate()
   await getTeacherList()
   await getclassRoom()
  dialogValue.value = true;
  buttonType.value = "add";
  echo.value = {
    name:"",
    course_category_id:'',
    status:'',
    date:[],
    num:0,
    admins_id:'',
    remark:'',
    digest:'',
    week:'',
    sort:0,
    price:'',
    classroom_id:'',
  };
};

// 表格行内操作按钮
const rowControl = ["rowedit","rowcopy", "rowdel"];

/**表格行内操作
 * @row {object} 行内数据
 * @type {string} 点击按钮类型
 */
const onRowControlClick = async (row, type) => {
  console.log(row);
  if (type == "rowedit") {
    await getCourseCate()
    await getTeacherList()
    await getclassRoom()
    const { id, name,course_category_id, status, time,start_time, end_time,num,admins_id,classroom_id,remark,digest,week,sort,price } = row;
    echo.value ={ id, name, course_category_id, status,time,num,admins_id,classroom_id,remark,digest,sort,price }
    echo.value.week = week.split(',')
    echo.value.admins_id = admins_id.split(',').map(Number)
    echo.value.classroom_id = Number(classroom_id)
    // echo.value.classroom_id = classroom_id.split(',').map(Number)
    echo.value.date = []
    echo.value.date.push(start_time) 
    echo.value.date.push(end_time)
    buttonType.value = "edit";
    dialogValue.value = true;
  }
  if (type == 'rowcopy') {
    await getCourseCate()
    await getTeacherList()
    await getclassRoom()
    const { course_category_id, status,time, start_time, end_time,num,admins_id,classroom_id,remark,digest,week,sort,price } = row;
    echo.value ={  course_category_id, status,time, num,admins_id,classroom_id,remark,digest,sort,price }
    echo.value.week = week.split(',')
    echo.value.admins_id = admins_id.split(',').map(Number)
    echo.value.classroom_id = Number(classroom_id)
    // echo.value.classroom_id = classroom_id.split(',').map(Number)
    echo.value.date = []
    echo.value.date.push(start_time) 
    echo.value.date.push(end_time)
    echo.value.name = ''
    buttonType.value = "copy";
    dialogValue.value = true;
  }
  if (type == 'rowdel') {
        messageBox().then(async () => {
        await delTableList(row.id) 
    })
  }
}
// 刪除課程
const delTableList = async (id)=>{
  const data = await delCourse(id)
  if (data.code == 200) {
   await tableList(obj)
    message('成功刪除課程')
  }else{
    message('刪除課程失敗')
  }
}
/** 多选
 * @selected {Array} 被选中的行
 */
const ids = ref('')
const onSelectionChange = (e) => {
  let row_id = []
  e.forEach(e => {
    row_id.push(e.id)
  });
  ids.value = row_id.toString()
  delsable.value = e.length === 0;
};
const delsHeader = () => {
      messageBox().then(async () => {
        delTableList(ids.value )
    }).catch(e=>{})
};
/**
 * @e {number} 分页操作后的值（当前页|改变后的每页条数）
 * @type {string} <current|size> 分页操作类型（当前页改变|每页条数改变）
 */
const onPageChange = async({ e, type }) => {
  console.log(e, type);
  if (type == "current") {
    obj.page = e
  }
  if (type == "size") {
     obj.page = 1
    obj.limit = e
  }
  await tableList()
};
// 弹窗
const dialogVisible = ref(false);

const handleClose = (done) => {
  dialogVisible.value = false;
};

const tableData = ref([])
const obj = reactive({
  school_id:localStorage.getItem('school_id'),
  page: page.current_page,
  limit: page.per_page,
  name: "",
  status: "",
  date: "",
  time:'',
});
const tableList = async ()=>{
  loading()
  const data = await course(obj)
  if (data.code == 200) {
    data.data.data.map(e=>e.status == 1 ?  e.statuss = '正常' :    e.statuss = '禁用')
    tableData.value = data.data.data
    page.current_page = data.data.current_page
    page.per_page = data.data.per_page
    page.total = data.data.total
    console.log( tableData.value);
  }
  closeLoading()
}

const pageRefresh = async () => {
  await tableList();
};
onMounted(() => {
  tableList();
});
// const dialogForm = ref(null);
// const DialogCofirm = () => {
//   dialogForm.value.submit((e) => {
//     console.log(e);
//   });
// };
</script>

<style lang="less" scoped>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.box {
  padding: 16px 33px;
}
</style>